//
//  WJTimeAgoController.m
//  JerryIos
//
//  Created by 王军 on 2018/2/13.
//  Copyright © 2018年 王军. All rights reserved.
//

#import "WJTimeAgoController.h"
#import "NSDate+DateTools.h"

@interface WJTimeAgoController ()

@property (weak, nonatomic) IBOutlet UILabel *TimeAgoLabel;
@property (weak, nonatomic) IBOutlet UISlider *TimeAgoSlider;
@property (weak, nonatomic) IBOutlet UILabel *SecondsLabel;
@property (weak, nonatomic) IBOutlet UILabel *MinutesLabel;
@property (weak, nonatomic) IBOutlet UILabel *HoursLabel;
@property (weak, nonatomic) IBOutlet UILabel *DaysLabel;
@property (weak, nonatomic) IBOutlet UILabel *WeeksLabel;
@property (weak, nonatomic) IBOutlet UILabel *MonthsLabel;
@property (weak, nonatomic) IBOutlet UILabel *YearsLabel;

@property NSTimer *updateTimer;
@property NSDate *selectedDate;
@property NSDateFormatter *formatter;

@end

@implementation WJTimeAgoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"Time Ago";
    [self setupData];
}

-(void)setupData {
    //设置日期格式
    self.formatter = [[NSDateFormatter alloc] init];
    [self.formatter setDateFormat:@"HHmm MMMM d yyyy"];
    
    //初使化数据
    self.selectedDate = [self.formatter dateFromString:@"0000 November 5 1605"];
    self.TimeAgoSlider.value = [self.selectedDate timeIntervalSinceNow];
    [self updateUI];
    
    //定期更新UI
    [self updateUIByTimer];
}

//updateUI
-(void)updateUI{
    //Account for now
    if (self.TimeAgoSlider.value == 0) {
        self.selectedDate = [NSDate date];
    }
    
    //设置标签
    self.TimeAgoLabel.text = [self.formatter stringFromDate:self.selectedDate];
    self.SecondsLabel.text = [NSString stringWithFormat:@"%.0f", self.selectedDate.secondsAgo];
    self.MinutesLabel.text = [NSString stringWithFormat:@"%.0f", self.selectedDate.minutesAgo];
    self.HoursLabel.text = [NSString stringWithFormat:@"%.0f", self.selectedDate.hoursAgo];
    self.DaysLabel.text = [NSString stringWithFormat:@"%ld", (long)self.selectedDate.daysAgo];
    self.WeeksLabel.text = [NSString stringWithFormat:@"%ld", (long)self.selectedDate.weeksAgo];
    self.MonthsLabel.text = [NSString stringWithFormat:@"%ld", (long)self.selectedDate.monthsAgo];
    self.YearsLabel.text = [NSString stringWithFormat:@"%ld", (long)self.selectedDate.yearsAgo];
}

-(void)updateUIByTimer {
    //设置一个定时器，定时更新UI
    self.updateTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateUI) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.updateTimer forMode:NSRunLoopCommonModes];
}

- (IBAction)sliderValueDidChange:(UISlider *)sender {
    self.selectedDate = [NSDate dateWithTimeIntervalSinceNow:sender.value];
    [self updateUI];
}
@end
